// 动态规划

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        std::vector<int> leftMax(n);
        leftMax[0] = height[0];
        for(int i = 1; i < n; ++i)
        {
            leftMax[i] = max(leftMax[i-1], height[i]);
        }
        std::vector<int> rightMax(n);
        rightMax[n-1] = height[n-1];
        for(int i = n - 2; i >= 0; --i)
        {
            rightMax[i] = max(rightMax[i+1], height[i]);
        }
        int count = 0;
        std::vector<int> result(n);
        for(int i = 0; i < n; ++i)
        {
            result[i] = min(rightMax[i], leftMax[i]);
            count += result[i] - height[i];
        }
        return count;
    }
};


// 双指针
class Solution {
public:
    int trap(vector<int>& height) {
        int count = 0, left = 0, right = height.size() - 1, leftMax = 0, rightMax = 0;
        while(left < right)
        {
            leftMax = max(leftMax, height[left]);
            rightMax = max(rightMax, height[right]);
            if(height[left] < height[right])
            {
                count += leftMax - height[left];
                ++left;
            }
            else
            {
                count += rightMax - height[right];
                --right;
            }
        }
        return count;
    }
};
